import yaml
import os

class ReadYaml:
    def __init__(self, filename: str):
        self.filename = filename
        self._cache = None
        self._last_modified_time = None

    def _load_yaml(self) -> dict:
        """重新加载 YAML 配置文件"""
        try:
            with open(self.filename, "r", encoding="utf-8") as fp:
                return yaml.safe_load(fp)  # 直接读取 YAML 内容
        except FileNotFoundError:
            raise FileNotFoundError(f"文件 {self.filename} 未找到")
        except yaml.YAMLError as e:
            raise ValueError(f"YAML 文件解析错误: {e}")

    @property
    def read_yaml(self) -> dict:
        """读取 YAML 配置文件，如果配置文件有变化则重新加载"""
        try:
            current_modified_time = os.path.getmtime(self.filename)

            # 如果缓存为空或文件修改时间变化，重新加载配置
            if self._cache is None or self._last_modified_time != current_modified_time:
                self._cache = self._load_yaml()
                self._last_modified_time = current_modified_time

            return self._cache
        except Exception as e:
            raise e
